<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>{{$t('Add_controllers')}}</h3>
      <el-form ref="dataForm" :rules="rules" :model="admin" label-width="150px">
        <el-form-item :label="$t('Partner_name')" prop="nickName">
          <el-input v-model="admin.nickName"/>
        </el-form-item>

        <el-form-item :label="$t('员工代号')" prop="code">
          <el-input v-model="admin.code" onkeyup="this.value=this.value.replace(/[ ]/g,'')" />
        </el-form-item>
        <el-form-item :label="$t('社保号码')" prop="socialSecurityNumber">
          <el-input v-model="admin.socialSecurityNumber" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('性别')" prop="gender">
          <el-select v-model="admin.gender" :placeholder="$t('请选择')" clearable>
            <el-option :value="1" :label="$t('其他')"></el-option>
            <el-option :value="2" :label="$t('女')"></el-option>
            <el-option :value="3" :label="$t('男')"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('生日')" prop="birthday">
          <el-date-picker clearable
              class="filter-date-item"
              v-model="admin.birthday"
              type="date"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('Partner_picture')" prop="avatar">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadAvatar"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="admin.avatar" :src="admin.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
            <label v-if="admin.avatar" class="el-upload-list__item-status-label avatar-uploader__status_label" @click.stop="handleRemove()"><i class="el-icon-delete"></i></label>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('Address')" prop="location">
          <el-select v-model="admin.locationCountry" :placeholder="$t('请选择')" filterable @change="(value) => changeCountry(value)">
            <el-option
              v-for="country in countrys"
              :key="country.id"
              :label="country.nameCn || country.nameEn"
              :value="country.id">
            </el-option>
          </el-select>

          <el-select v-model="admin.locationProvince"  :placeholder="$t('请选择')" filterable @change="(value) => changeProvince(value)">
            <el-option
              v-for="province in provinces"
              :key="province.id"
              :label="province.nameCn || province.nameEn"
              :value="province.id">
            </el-option>
          </el-select>

          <el-select v-model="admin.locationCity"  :placeholder="$t('请选择')" filterable>
            <el-option
              v-for="city in citys"
              :key="city.id"
              :label="city.nameCn || city.nameEn"
              :value="city.id">
            </el-option>
          </el-select>

          <p></p>

          <el-input v-model="admin.location"/>
        </el-form-item>
        <el-form-item :label="$t('邮编')" prop="postalCode">
          <el-input v-model="admin.postalCode" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('Contact_number')" prop="mobile">
        <el-input v-model="admin.mobile" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
      </el-form-item>
        <el-form-item :label="$t('邮箱')" prop="email">
          <el-input v-model="admin.email" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('Partner_role')" prop="roleIds">
          <el-col>
            <el-select v-model="admin.roleIds" :placeholder="$t('请选择')" multiple collapse-tags>
              <el-option v-for="item in roles" :value="item.value" :label="item.label"/>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('Store_belong')" prop="shopId">
          <el-select v-model="admin.shopId" :placeholder="$t('请选择')" :clearable="!shop" filterable>
            <el-option v-for="item in shops" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('Account_login')" prop="username">
          <el-input v-model="admin.username"/>
        </el-form-item>
        <el-form-item :label="$t('Please_enter_password')" prop="password">
          <el-input v-model="admin.password" show-password/>
        </el-form-item>
<!--        <el-form-item label="确认密码" prop="name">
          <el-input v-model="admin.confirm" show-password/>
        </el-form-item>-->
        <el-form-item :label="$t('备注信息')">
          <el-input v-model="admin.remark" type="textarea"/>
        </el-form-item>
      </el-form>
      <div class="op-container" align="center">
        <el-button icon="el-icon-error" type="info" plain1 @click="handleCancel">{{$t('Cancel')}}</el-button>
        <el-button icon="el-icon-success" type="warning" plain1 p-m  @click="handleCreate">{{$t('Add_controllers')}}</el-button>
      </div>
    </el-card>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
  .avatar-uploader__status_label{
    display: block;
    color: red;
  }
</style>

<script>
  import { uploadPath } from '@/api/storage'
  import { createAdmin } from '@/api/admin'
  import { roleOptions } from '@/api/role'
  import { getToken } from '@/utils/auth'
  import { getShopAll } from '@/api/shop'
  import { listCountryRegion, listSubRegion } from '@/api/region'
  import store from '@/store'

  export default {
    name: 'sysAdminCreate',
    data() {
      const validateRegion = (rule, value, callback) => {
        if (this.admin.locationCountry
          && this.admin.locationProvince
          && this.admin.locationCity
          && this.admin.location) {
          callback()
        } else {
          callback(new Error('请选择完整的区域信息'))
        }
      }

      return {
        // 当前店铺
        shop: store.state.user.shop,
        uploadPath,
        admin: {
          avatar:'',
          locationCountry: undefined,
          locationProvince: undefined,
          locationCity: undefined,
          location: undefined,
          birthday: undefined
        },
        roles: [],
        shops: [],
        countrys: [],
        provinces: [],
        citys: [],
        rules: {
          username: [
            { required: true, message: this.$t('Controller_name_cannot_be_empty'), trigger: 'blur' }
          ],
          password: [{ required: true, message: this.$t('Password_cannot_be_empty'), trigger: 'blur' },
            { min: 6, max: 16, message: this.$t('Password_length_from_6_-_16_characters'), trigger: 'blur' }],
          code: [
            { required: true, message: this.$t('员工代号不能为空'), trigger: 'blur' }
          ],
          nickName: [
            { required: true, message: this.$t('员工名称不能为空'), trigger: 'blur' }
          ],
          socialSecurityNumber: [
            { required: true, message: this.$t('社保号码不能为空'), trigger: 'blur' }
          ],
          gender: [
            { required: true, message: this.$t('性别不能为空'), trigger: 'blur' }
          ],
          birthday: [
            { required: true, message: this.$t('生日不能为空'), trigger: 'blur' }
          ],
          location: [
            { required: true, validator: validateRegion, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: this.$t('联系电话不能为空'), trigger: 'blur' }
          ],
          email: [
            { required: true, message: this.$t('邮箱不能为空'), trigger: 'blur' }
          ],
          roleIds: [
            { required: true, message: this.$t('角色不能为空'), trigger: 'blur' }
          ],
          postalCode: [
            { required: true, message: this.$t('邮编不能为空'), trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      const shopId = this.$route.query.shopId || null
      roleOptions(shopId).then(res => {
        this.roles = res.data.data.list
      })
      getShopAll().then(res=>{
        // console.log(res.data.data);
        this.shops = res.data.data
      })
      listCountryRegion().then(response=>{
        this.countrys = response.data.data.list
      })

      // 初始化生日为当天
      this.admin.birthday = this.getFullDate(new Date())
    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    },
    methods: {
      handleCreate() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            createAdmin(this.admin)
              .then(() => {
                this.$notify.success({
                  title: this.$t('Success!'),
                  message: this.$t('New_controller_added_successfully')
                })

                // this.$router.push({path:'/shop/admin'})
                // 删除当前标签页，跳转至上一个页面
                this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
                this.$router.go(-1)
              })
              .catch(response => {
                this.$notify.error({
                  title: this.$t('Failed'),
                  message: this.$t(response.data.errmsg)
                })
              })
          }
        })
      },
      changeCountry (value) {
        this.provinces = []
        this.citys = []
        this.admin.locationProvince = undefined
        this.admin.locationCity = undefined

        let query = {
          id: value,
          type: 2
        }
        listSubRegion(query).then(response=>{
          this.provinces = response.data.data.list
        })
      },
      changeProvince (value) {
        this.citys = []
        this.admin.locationCity = undefined

        let query = {
          id: value,
          type: 2
        }
        listSubRegion(query).then(response=>{
          this.citys = response.data.data.list
        })
      },
      uploadAvatar: function(response) {
        this.admin.avatar = response.data.url
      },
      handleCancel(){
        // this.$router.push({ path: '/shop/admin'})

        // 删除当前标签页，跳转至上一个页面
        this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
        this.$router.go(-1)
      },
      handleRemove(){
        this.admin.avatar = undefined
      },
      getFullDate(targetDate) {
        var D, y, m, d;
        if (targetDate) {
            D = new Date(targetDate);
            y = D.getFullYear();
            m = D.getMonth() + 1;
            d = D.getDate();
        } else {
            y = fullYear;
            m = month;
            d = date;
        }
        m = m > 9 ? m : '0' + m;
        d = d > 9 ? d : '0' + d;
        return y + '-' + m + '-' + d;
      }
    }
  }
</script>

<style scoped>

</style>
